package cn.yoaket.util;

import cn.yoaket.exception.ContextException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Alex
 */
public class XmlPhrase {

    private XmlPhrase(){}

    private static Document load(String path) throws ContextException {
        Document document;
        try {
            SAXReader saxReader = new SAXReader();
            // 读取XML文件,获得document对象
            document = saxReader.read(new File(path));
        } catch (DocumentException e) {
            throw new ContextException(ContextException.Type.FORMAT_ERROR);
        }
        return document;
    }

    public static List<BeanDefinition> phrase(String path) throws ContextException {
        var defs = new ArrayList<BeanDefinition>();
        Document dom =load(path);
        //节点找不到异常
        Element root = dom.getRootElement();
        if(root == null || !"beans".equals(root.getName())){
            throw new ContextException(ContextException.Type.FORMAT_ERROR);
        }
        var beans = root.elements("bean");
        for(var bean: beans){
            //id和class没有的异常
            BeanDefinition def = new BeanDefinition(bean.attributeValue("id"),bean.attributeValue("class"));
            if(def.id==null || def.className==null){
                throw new ContextException(ContextException.Type.PARAM_ERROR);
            }
            List<Element> properties = bean.elements("properties");
            for (var property: properties){
                //获取name 找不到抛异常
                var name = property.attributeValue("name");
                var value = property.attributeValue("value");
                //如果两中间有空抛出异常
                if(name==null || value==null){
                    throw new ContextException(ContextException.Type.PARAM_ERROR);
                }
                def.addFiled(name,value);
            }
            defs.add(def);
        }
        return defs;
    }

}
